# -*- coding: utf-8 -*-
# @File : .py
# @Author : ZhouHang
# @Date : 18-8-23
# @Desc :
from flask import abort, jsonify
from flask import current_app
from flask import g
from flask import request
from flask import session

from info import constants, db
from info.models import User, News, Comment, CommentLike
from info.modules.news import news_blu
from flask import render_template

from info.utils.common import user_login_data
from info.utils.response_code import RET






@news_blu.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):
    user = g.user
    news_list = News.query.order_by(News.clicks.desc()).limit(6)
    # print(news_list)
    click_list = []
    for news in news_list if news_list else None:
        click_list.append(news.to_basic_dict())

    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        abort(404)

    if not news:
        # 返回数据未找到的页面
        abort(404)
    news.clicks += 1
    is_collected = False
    if user:
        if news in user.collection_news:
            is_collected = True


    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as error :
        current_app.logger.error(error)

    user = g.user
    comment_like_ids = []
    if g.user:
        try:
            # 查询当前新闻下的所有评论id [1, 2, 3, 4, 5]
            comment_ids = [comment.id for comment in comments]
            # 　查询所有该用户在当前新闻下的所有点赞　的新闻id
            comment_likes = CommentLike.query.filter(CommentLike.comment_id.in_(comment_ids), CommentLike.user_id == g.user.id).all()
            comment_like_ids = [comment_like.comment_id for comment_like in  comment_likes]
        except Exception as error:
            current_app.logger.error(error)
    comment_dict_li = []
    for comment in comments:
        comment_dict = comment.to_dict()
        comment_dict["is_like"] = False
        if comment.id in comment_like_ids:
            comment_dict["is_like"] = True
        comment_dict_li.append(comment_dict)
    # db.session.commit()


    # 粉丝
    is_followed = False
    # 判断用户是否收藏过该新闻
    # is_collected = False
    # 如果当前登陆用户和作者存在
    if g.user and news.user:
        if news.user.followers.filter(User.id == g.user.id).count() > 0:
            is_followed = True

    data = {
            "news": news.to_dict(),
            'user_info': user.to_dict() if user else None,
             "click_news": click_list,
            "is_collected" : is_collected,
            "comments": comment_dict_li,
            "is_followed" : is_followed
             }

    return render_template("news/detail.html", data = data)


@news_blu.route('/news_collect', methods = ["POST"])
@user_login_data
def collect_cancle_news():

    user = g.user
    if not user:
        return jsonify(errno = RET.SESSIONERR, errmsg = "用户未登陆")

    news_id = request.json.get("news_id")
    action = request.json.get("action")
    if not all([news_id, action]) :
        return jsonify(errno = RET.PARAMERR, errmsg = "参数错误")
    if action not in ("collect", "cancel_collect"):
        return jsonify(errno = RET.DATAERR, errmsg = "参数错误")
    try:
        news_id = int(news_id)
    except Exception as error:
        current_app.logger.error(error)
        return jsonify(errno = RET.DATAERR, errmsg = "参数错误")
    try:
        news = News.query.get(news_id)
    except Exception as error:
        current_app.logger.error(error)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
    if not news:
        return jsonify(errno = RET.NODATA, errmsg = "当前数据不存在")

    if action == "collect":
        if news not in user.collection_news:
            user.collection_news.append(news)

    else:
        if news in user.collection_news:
            user.collection_news.remove(news)

    return jsonify(errno = RET.OK, errmsg = "操作成功")


@news_blu.route('/news_comment', methods = ["POST"])
@user_login_data
def add_news_comment():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    # 获取参数
    data_dict = request.json
    news_id = data_dict.get("news_id")
    comment_str = data_dict.get("comment")
    parent_id = data_dict.get("parent_id")

    if not all([news_id, comment_str]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据失败")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="该新闻不存在")

    # 初始化模型，保存数据
    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news_id
    comment.content = comment_str
    if parent_id:
        comment.parent_id = parent_id

    # 保存到数据库
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存评论数据失败")

    # 返回响应
    return jsonify(errno=RET.OK, errmsg="评论成功", data=comment.to_dict())


@news_blu.route('/comment_like', methods=["POST"])
@user_login_data
def set_comment_like():
    """评论点赞"""
    if not g.user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    # 获取参数
    comment_id = request.json.get("comment_id")
    news_id = request.json.get("news_id")
    action = request.json.get("action")

    # 判断参数
    if not all([comment_id, news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ("add", "remove"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 查询评论数据
    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据失败")

    if not comment:
        return jsonify(errno=RET.NODATA, errmsg="评论数据不存在")


    # 取到对应的点赞模型
    comment_like = CommentLike.query.filter(CommentLike.user_id == g.user.id, CommentLike.comment_id == comment_id).first()
    if action == "add":
        """点赞"""
        if  not comment_like:
            comment_like = CommentLike()
            try:
                comment_like.user_id = g.user.id
                comment_like.comment_id = comment_id
                db.session.add(comment_like)
                comment.like_count += 1
            except Exception as error:
                current_app.logger.error(error)
                return jsonify(errno=RET.DBERR, errmsg="保存数据失败")
    else:
        # 删除点赞数据
        comment_like = CommentLike.query.filter_by(comment_id=comment_id, user_id=g.user.id).first()
        if comment_like:
            try:
                db.session.delete(comment_like)
            # 减小点赞条数
                comment.like_count -= 1
            except Exception as error:
                current_app.logger.error(error)
                return jsonify(errno = RET.DATAERR, errmsg = "取消点赞失败")
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="操作失败")
    return jsonify(errno=RET.OK, errmsg="操作成功")



@news_blu.route('/followed_user', methods=["POST"])
@user_login_data
def followed_user():
    """关注/取消关注用户"""
    if not g.user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    user_id = request.json.get("user_id")
    action = request.json.get("action")

    if not all([user_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ("follow", "unfollow"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 查询到关注的用户信息
    try:
        target_user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据库失败")

    if not target_user:
        return jsonify(errno=RET.NODATA, errmsg="未查询到用户数据")

    # 根据不同操作做不同逻辑
    if action == "follow":
        if target_user.followers.filter(User.id == g.user.id).count() > 0:
            return jsonify(errno=RET.DATAEXIST, errmsg="当前已关注")
        target_user.followers.append(g.user)
    else:
        if target_user.followers.filter(User.id == g.user.id).count() > 0:
            target_user.followers.remove(g.user)

    # 保存到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存错误")

    return jsonify(errno=RET.OK, errmsg="操作成功")


